package com.atguigu.gulimall.seckill.interceptor;

import com.atguigu.common.contrsant.AuthServerConstant;
import com.atguigu.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //访问路径
        String uri = request.getRequestURI();
        //路径匹配器
        // 此类型的请求，直接放行，无需登录，否则会报错
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/web/seckill/kill", uri);
        boolean match1 = antPathMatcher.match("/web/seckill/current-seckill-skus", uri);
//        boolean match1 = antPathMatcher.match("/web/seckill/seckill-sku-relation/**", uri);
        if (match || match1) return true;

        MemberResponseVo memberTO = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberTO != null) {
            threadLocal.set(memberTO);
            return true;
        } else {
            request.getSession().setAttribute("msg", "请先进行登录！");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
